<template>
    <!-- 导航栏 -->
    <van-nav-bar
        title="购物车"
        left-text="返回"
        left-arrow
        fixed
        placeholder
        z-index="1000"
        @click-left="OnBack"
    />

    <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="OnLoad"
        >
            <van-checkbox-group v-model="CheckedArr" ref="CheckboxGroup" @change="OnToggleGroup">
                <div class="cart" v-for="(item,index) in CartList" :key="item.id">
                    <!-- 滑动单元格 -->
                    <van-swipe-cell>
                        <van-checkbox :name="item.id"></van-checkbox>
                        <!-- 商品卡片 -->
                        <van-card
                            :thumb="item.product.thumb_text"
                            @click-thumb="ToProductInfo(item.product.id)"
                        >
                            <template #title>
                                <div class="title" @click="ToProductInfo(item.product.id)">{{ item.product.name }}</div>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-if="item.attrs">
                                <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-else>
                                <van-tag class="tag" type="danger">无商品规格</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <template #tags>
                                <div class="price">单价：￥{{ item.price }}</div>
                            </template>

                            <template #price>
                                <div class="price">合计：￥{{ item.total }}</div>
                            </template>

                            <!-- 卡片的商品数量 步进器 -->
                            <template #num>
                                <van-stepper v-model="item.nums" disable-input :name="index" :max="item.product.live_stock ? item.product.live_stock : item.product.stock" @change="OnCartUpdate" />
                            </template>
                        </van-card>

                        <!-- 滑动单元格插槽 右侧滑动 -->
                        <template #right>
                            <van-button
                                square
                                text="删除"
                                type="danger"
                                class="delete-button"
                                @click="OnDel(item,index)"
                            />
                        </template>
                    </van-swipe-cell>
                </div>
            </van-checkbox-group>

            <van-back-top :bottom="'80'" />
        </van-list>
    </van-pull-refresh>

    <div style="height: 50px;"></div>

    <!-- 提交动作栏 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="OnSubmit">
        <van-checkbox v-model="CheckedAll" :indeterminate="IsIndeterminate" @change="OnToggle">全选</van-checkbox>
    </van-submit-bar>
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const CartList = ref([]);
const refreshing = ref(false);
const finished = ref(false);
const loading = ref(false);
// 不确认全选状态
const IsIndeterminate = ref(false);
const page = ref(1);
// 复选框选中的数据
const CheckedArr = ref([]);
// 全选中
const CheckedAll = ref(false);
// 复选框Dom
const CheckboxGroup = ref(null);
// 接收一个 action 参数，判断是否在商品详情过来的
const action = ref(proxy.$route.query.action ?? '');

// 下拉刷新
const OnRefresh = () =>
{
     // 清空查询参数
    finished.value = false;
    page.value = 1;
    CartList.value = [];
    loading.value = true;

    // 加载数据方法
    setTimeout(OnLoad,1500);
}

// 上拉加载
const OnLoad = async () =>
{
    if(refreshing.value === true) refreshing.value = false;

    const params = {
        busid:business.value.id,
        page:page.value
    }

    const result = await proxy.$http.post({
        url:'/cart/index',
        params
    });

    loading.value = false;

    if(result.code === 1)
    {
        // 合并数组
        CartList.value = CartList.value.concat(result.data.list);
        const count = result.data.count;

        // 把attrs属性字符串转成对象
        CartList.value.map(item => item.attrs = JSON.parse(item.attrs));

        // 如果没有更多数据了，就说明已经加载到底了
        if(CartList.value.length === count)
        {
            finished.value = true;

            return false;
        }

        page.value = page.value + 1;
    }else
    {
        finished.value = true;

        proxy.$fail(result.msg);
    }
}

// 提交订单事件
const OnSubmit = () =>
{
    if(CheckedArr.value.length <= 0)
    {
        proxy.$fail('请选择结算的商品');

        return false;
    }

    // 跳转确认订单页面
    proxy.$router.push({
        path:'/cart/confirm',
        query:{
            cartids:CheckedArr.value.join(',')
        }
    });
}

// 控制提交栏全选状态
const OnToggleGroup = () =>
{
    CheckedAll.value = CheckedArr.value.length === CartList.value.length ? true : false;
    IsIndeterminate.value = CheckedArr.value.length > 0 && CheckedArr.value.length !== CartList.value.length ? true : false;
}

// 提交栏的全选事件
const OnToggle = (value) =>
{
    CheckboxGroup.value.toggleAll(value);
}

const OnCartUpdate = async (value,{ name }) =>
{
    const index = name;

    const params = {
        cartid:CartList.value[index].id,
        nums:value,
        busid:business.value.id
    }

    const result = await proxy.$http.post({
        url:'/cart/edit',
        params
    });

    if(result.code === 1)
    {
        CartList.value[name].total = (parseFloat(CartList.value[name].price) * value).toFixed(2); 
    }else{
        proxy.$fail(result.msg);
    }
}


// 选中结算商品计算总价
const total = computed(() => {
    let total = 0;

    if(CheckedArr.value.length > 0)
    {
        CartList.value.map(item =>
        {
            if(CheckedArr.value.includes(item.id)) total += parseFloat(item.total);
        })
    }

    return total * 100;
})

// 顶部导航栏返回事件
const OnBack = () => {
    if(action.value === 'info')
    {
        proxy.$router.back();
    }else{
        proxy.$router.push('/');
    }
};

const ToProductInfo = () => proxy.$router.push('/product/info');
</script>

<style scoped>
@import url('/assets/css/cart.css');
</style>